<?php
class Site_Model_Signup
{
    public $typeAccess = null;
	private $userData;
	
	public function __construct()
	{
		$this->userData = new Zend_Session_Namespace();
	}
	
	public function form($data = null, $type)
	{
		if( $type == 'full') return $this->fullForm( $data );
		
		if( $type == 'confirm') return $this->confirmForm( $data );
		
		if( $type == 'newUser') return $this->newUserForm( $data );
		
	}
	
	public function save($post)
	{
		$post['clientOption'] = $post['clientOption'][0];
		
		$result = $this->fullValidate( $post );
		
		if( $result['error'] >= 1 ) 
		{
			return $result;
		}
		else
		{
			$data['signup']['name'] = $post['name'];
			$data['signup']['email'] = $post['email'];
			$data['signup']['password'] = md5($post['password']) ;
			$data['signup']['areaCode'] = $post['areaCode'];
			$data['signup']['phoneNumber'] = $post['phoneNumber'];
			$data['signup']['street'] = $post['street'];
			$data['signup']['number'] = $post['number'];
			$data['signup']['complement'] = $post['complement'];
			$data['signup']['district'] = $post['district'];
			$data['signup']['postalCode'] = $post['postalCode'];
			$data['signup']['city'] = $post['city'];
			$data['signup']['state'] = $post['state'];
			
			$signup = new Application_Model_Db_Signup();
			$signup->insert( $data['signup'] );
			
			$idSignup = $signup->getAdapter()->lastInsertId();
			
			$data['order']['idSignup'] = $idSignup;
			$data['order']['shippingType'] = $post['shippingType'];
			$data['order']['buyIdentity'] = md5( $idSignup . date('YmdHis') . rand(100001,999999) );
			
			$this->userData->buyIdentity = $data['order']['buyIdentity'];
			
			$this->insertCart($data);
			
			$this->registerUser( $idSignup, $data['signup']['name'], $data['signup']['email'] );
			
			
			return array( 'error' => 0 );
		}
	}
	
	public function saveNewUser($post)
	{
		$result = $this->simpleValidate( $post );
		
		if( $result['error'] >= 1 ) 
		{
			return $result;
		}
		else
		{
			$data['signup']['name'] = $post['name'];
			$data['signup']['email'] = $post['email'];
			$data['signup']['password'] = md5($post['password']) ;
			$data['signup']['areaCode'] = $post['areaCode'];
			$data['signup']['phoneNumber'] = $post['phoneNumber'];
			$data['signup']['street'] = $post['street'];
			$data['signup']['number'] = $post['number'];
			$data['signup']['complement'] = $post['complement'];
			$data['signup']['district'] = $post['district'];
			$data['signup']['postalCode'] = $post['postalCode'];
			$data['signup']['city'] = $post['city'];
			$data['signup']['state'] = $post['state'];
			
			$signup = new Application_Model_Db_Signup();
			
			
			if( isset($this->userData->id) )
			{
				$signup->update( $data['signup'], 'idSignup = ' . $this->userData->id);
				$idSignup = $this->userData->id;
			}
			else
			{
				$signup->insert( $data['signup'] );
				$idSignup = $signup->getAdapter()->lastInsertId();
			}
						
			$this->registerUser( $idSignup, $data['signup']['name'], $data['signup']['email'] );
			return array( 'error' => 0 );
		}
	}
	
	public function updateConfirmUser($post)
	{
		$result = $this->adressValidate( $post );
		
		if( $result['error'] >= 1 ) 
		{
			return $result;
		}
		else
		{
			$data['signup']['street'] = $post['street'];
			$data['signup']['number'] = $post['number'];
			$data['signup']['complement'] = $post['complement'];
			$data['signup']['district'] = $post['district'];
			$data['signup']['postalCode'] = $post['postalCode'];
			$data['signup']['city'] = $post['city'];
			$data['signup']['state'] = $post['state'];
			
			$signup = new Application_Model_Db_Signup();
			$signup->update( $data['signup'], 'idSignup = ' . $this->userData->id);
			
			$data['order']['idSignup'] = $this->userData->id;
			$data['order']['shippingType'] = $post['shippingType'];
			$data['order']['buyIdentity'] = md5( $this->userData->id . date('YmdHis') . rand(100001,999999) );
			
			$this->insertCart($data);
			
			return array( 'error' => 0 );
		}
	}
	
	private function insertCart($data)
	{
		$order = new Application_Model_Db_Order();
		$cart = Site_Model_ShoppingCart::get_instance();
		foreach( $cart->getItens() as $key => $pack )
		{
			$item['idSignup'] = $data['order']['idSignup'];
			$item['shippingType'] = $data['order']['shippingType'];
			$item['buyIdentity'] = $data['order']['buyIdentity'];
			$item['postalCode'] = str_replace('-','',$data['signup']['postalCode']);
			$item['file'] = $pack['cart']->gallery[0]->file;
			$item['name'] = $pack['cart']->product->name;
			$item['color'] = $pack['cart']->colors[ $pack['cart']->detail->idColor ];
			$item['size'] = $pack['cart']->sizes[ $pack['size'] ];
			$item['cost'] = $pack['cart']->detail->cost;
			
			$item['nCdFormato'] = $pack['cart']->product->nCdFormato;
			$item['nVlPeso'] = $pack['cart']->product->nVlPeso;
			$item['nVlAltura'] = $pack['cart']->product->nVlAltura;
			$item['nVlComprimento'] = $pack['cart']->product->nVlComprimento;
			$item['nVlLargura'] = $pack['cart']->product->nVlLargura;
			$item['nVlDiametro'] = $pack['cart']->product->nVlDiametro;
			
			$frete = new Site_Model_FreteCorreios();
			$frete->nCdServico = $data['order']['shippingType'];
			$frete->sCepDestino = $item['postalCode'];
			
			$frete->nCdFormato =  $pack['cart']->product->nCdFormato;
			$frete->nVlPeso = $pack['cart']->product->nVlPeso;
			$frete->nVlAltura = $pack['cart']->product->nVlAltura;
			$frete->nVlComprimento = $pack['cart']->product->nVlComprimento;
			$frete->nVlLargura = $pack['cart']->product->nVlLargura;
			$frete->nVlDiametro = $pack['cart']->product->nVlDiametro;
			
			$result = $frete->getFrete();
			 
			$item['shippingCost'] = $result->error ? 0 : str_replace(',','.',$result->valor);
			
			$order->insert( $item );
		}
		$this->userData->buyIdentity = $data['order']['buyIdentity'];
	}
	
	public function login($post)
	{
		$post['clientOption'] = $post['clientOption'][0];
		
//		$order = new Application_Model_Db_Order();
		$signup = new Application_Model_Db_Signup();
		$user = $signup->fetchRow( 'password = "' . md5($post['password']) . '" AND email = "' . $post['email'] . '"' );
		
		if( !isset($user->idSignup) ) 
		{
			return array( 'error' => 1, 'message' => 'Usuário e/ou senha inválidos', 'post' => $post);
		}
		else 
		{
			$idSignup = $user->idSignup;
			/*
			$data['order']['idSignup'] = $idSignup;
			$data['order']['shippingType'] = $post['shippingType'];
			$data['order']['buyIdentity'] = md5( $idSignup . date('YmdHis') . rand(100001,999999) );
			
			$this->userData->buyIdentity = $data['order']['buyIdentity'];
			
			$cart = Site_Model_ShoppingCart::get_instance();
			foreach( $cart->getItens() as $key => $pack )
			{
				$item['idSignup'] = $data['order']['idSignup'];
				$item['shippingType'] = $data['order']['shippingType'];
				$item['buyIdentity'] = $data['order']['buyIdentity'];
				$item['file'] = $pack['cart']->gallery[0]->file;
				$item['name'] = $pack['cart']->product->name;
				$item['color'] = $pack['cart']->colors[ $pack['cart']->detail->idColor ];
				$item['size'] = $pack['cart']->sizes[ $pack['size'] ];
				$item['cost'] = $pack['cart']->detail->cost;
				$order->insert( $item );
			}
			*/
			$this->registerUser( $idSignup, $user->name, $user->email );
			return array( 'error' => 0 );
		}
	}
	
	public function logout()
	{
		$this->userData->id = null;
		$this->userData->name = null;
		$this->userData->email = null;
	}
	
	public function registerUser($idSignup, $name, $email)
	{
		$this->userData->id = $idSignup;
		$this->userData->name = $name;
		$this->userData->email = $email;
	}
	
	public function getRegisterUser()
	{
		return $this->userData;
	}
	
	public function getLoggedUserData()
	{
		$signup = new Application_Model_Db_Signup();
		$data = ($this->userData->id) ? $signup->find( $this->userData->id )->current()->toArray() : null;
		
		return $data;
	}
	
	private function typeShipping()
	{
		$matrix = array(
    		''  => 'Selecione',
    		'41106' => 'Encomenda normal (PAC)',
    		'40010' => 'SEDEX' 
		);
		 
		return $matrix;
	}
	
	private function clientOptions()
	{
		$matrix = array(
    		'1' => 'Ainda não sou cliente',
    		'2' => 'Já sou cliente' 
		);
		 
		return $matrix;
	}
	
	private function fullValidate( $post )
	{
		$message = null;
		$signup = new Application_Model_Db_Signup();
		$user = $signup->fetchRow( 'email = "' . $post['email'] . '"' );
		
		if( $post['name'] == '' ) $message[] = 'Nome é Obrigatório';
		if( $post['email'] == '' ) $message[] = 'Email é Obrigatório';
		if( isset($user->idSignup) ) $message[] = 'Email ja cadastro';
		if( $post['password'] == '' ) $message[] = 'Senha é Obrigatório';
		if( $post['areaCode'] == '' ) $message[] = 'DDD é Obrigatório';
		if( $post['phoneNumber'] == '' ) $message[] = 'Telefone é Obrigatório';
		if( $post['postalCode'] == '' ) $message[] = 'CEP é Obrigatório';
		if( $post['street'] == '' ) $message[] = 'Endereço é Obrigatório';
		if( $post['number'] == '' ) $message[] = 'Numero é Obrigatório';
		if( $post['district'] == '' ) $message[] = 'Bairro é Obrigatório';
		if( $post['city'] == '' ) $message[] = 'Cidade é Obrigatório';
		if( $post['state'] == '' ) $message[] = 'Estado é Obrigatório';
		if( $post['shippingType'] == '' ) $message[] = 'Selecione o tipo do frete';

		return array( 'error' => count($message) , 'message' => $message, 'post' => $post);
	}
	
	private function adressValidate( $post )
	{
		$message = null;
		
		if( $post['postalCode'] == '' ) $message[] = 'CEP é Obrigatório';
		if( $post['street'] == '' ) $message[] = 'Endereço é Obrigatório';
		if( $post['number'] == '' ) $message[] = 'Numero é Obrigatório';
		if( $post['district'] == '' ) $message[] = 'Bairro é Obrigatório';
		if( $post['city'] == '' ) $message[] = 'Cidade é Obrigatório';
		if( $post['state'] == '' ) $message[] = 'Estado é Obrigatório';
		if( $post['shippingType'] == '' ) $message[] = 'Selecione o tipo do frete';

		return array( 'error' => count($message) , 'message' => $message, 'post' => $post);
	}
	
	private function simpleValidate( $post )
	{
		$message = null;
		$signup = new Application_Model_Db_Signup();
		$where = $signup->select();
		
		if( isset($this->userData->id) ) 
		{
			$where->where('email <> ?', $this->userData->email)->where('email = ?', $post['email']);
		}
		else
		{
			$where->where('email = ?', $post['email']);
		}
		
		$user = $signup->fetchRow( $where );
		
		if( $post['name'] == '' ) $message[] = 'Nome é Obrigatório';
		if( $post['email'] == '' ) $message[] = 'Email é Obrigatório';
		if( isset($user->idSignup) ) $message[] = 'Email ja cadastro';
		if( $post['password'] == '' ) $message[] = 'Senha é Obrigatório';
		if( $post['areaCode'] == '' ) $message[] = 'DDD é Obrigatório';
		if( $post['phoneNumber'] == '' ) $message[] = 'Telefone é Obrigatório';
		
		return array( 'error' => count($message) , 'message' => $message, 'post' => $post);
	}
	
	private function fullForm($data = null)
	{
		$form = new DataForm( 'cadastro-form' );
		$form->setData( $data );
		$form->form()->action = __LINKS__ . 'cadastro/save';
		$form->add( new RadioButton('clientOption', null, $this->clientOptions(), ($this->typeAccess ? 2 : 1) ) );
		$form->add( new InputText('name', '<b>* </b>Nome') );
		$form->fieldset( 'wp01' );
		$form->add( new InputText('email','<b>* </b>Email') );
		$form->fieldset( 'wp02' );
		$form->add( new InputPassword('password','<b>* </b>Senha') );
		$form->fieldset( 'wp03' );
		$form->add( new InputText('areaCode','<b>* </b>Telefone') );
		$form->add( new InputText('phoneNumber') );
		$form->label('title', 'Dados para entrega');
		$form->add( new InputText('postalCode','<b>* </b>CEP') );
		$form->fieldset( 'wp04' );
		$form->add( new InputText('street','<b>* </b>Endereço') );
		$form->fieldset( 'wp05' );
		$form->add( new InputText('number','<b>* </b>nº') );
		$form->fieldset( 'wp06' );
		$form->add( new InputText('complement','Complemento') );
		$form->fieldset( 'wp07' );
		$form->add( new InputText('district','<b>* </b>Bairro') );
		$form->fieldset( 'wp08' );
		$form->add( new InputText('city','<b>* </b>Cidade') );
		$form->fieldset( 'wp09' );
		$form->add( new InputText('state','<b>* </b>Estado') );
		$form->fieldset( 'wp10' );
		$form->label('title', 'Tipo de entrega');
		$form->add( new Select('shippingType','<b>* </b>Frete',$this->typeShipping(), 0) );
		$form->fieldset('buttons');
		$form->add( new InputSubmit('btn_save', 'ir para tela de pagamento') );
	
		return $form->get();
	}
	
	private function newUserForm($data = null)
	{
		$form = new DataForm( 'cadastro-form' );
		$form->setData( $data );
		$form->form()->action = __LINKS__ . 'cadastro/save-new-user';
		$form->add( new RadioButton('clientOption', null, $this->clientOptions(), ($this->typeAccess ? 2 : 1)) );
		$form->add( new InputText('name', '<b>* </b>Nome') );
		$form->fieldset( 'wp01' );
		$form->add( new InputText('email','<b>* </b>Email') );
		$form->fieldset( 'wp02' );
		$form->add( new InputPassword('password','<b>* </b>Senha') );
		$form->fieldset( 'wp03' );
		$form->add( new InputText('areaCode','<b>* </b>Telefone') );
		$form->add( new InputText('phoneNumber') );
		$form->label('title', 'Dados para entrega');
		$form->add( new InputText('postalCode','CEP') );
		$form->fieldset( 'wp04' );
		$form->add( new InputText('street','Endereço') );
		$form->fieldset( 'wp05' );
		$form->add( new InputText('number','nº') );
		$form->fieldset( 'wp06' );
		$form->add( new InputText('complement','Complemento') );
		$form->fieldset( 'wp07' );
		$form->add( new InputText('district','Bairro') );
		$form->fieldset( 'wp08' );
		$form->add( new InputText('city','Cidade') );
		$form->fieldset( 'wp09' );
		$form->add( new InputText('state','Estado') );
		$form->fieldset('buttons');
		$form->add( new InputSubmit('btn_save', 'enviar dados') );
	
		return $form->get();
	}
	
	private function confirmForm($data = null)
	{
		$form = new DataForm( 'cadastro-form' );
		$form->setData( $data );
		$form->form()->action = __LINKS__ . 'cadastro/update-confirm';
		$form->label('title', 'Dados para entrega');
		$form->add( new InputText('postalCode','<b>* </b>CEP') );
		$form->fieldset( 'wp04' );
		$form->add( new InputText('street','<b>* </b>Endereço') );
		$form->fieldset( 'wp05' );
		$form->add( new InputText('number','<b>* </b>nº') );
		$form->fieldset( 'wp06' );
		$form->add( new InputText('complement','Complemento') );
		$form->fieldset( 'wp07' );
		$form->add( new InputText('district','<b>* </b>Bairro') );
		$form->fieldset( 'wp08' );
		$form->add( new InputText('city','<b>* </b>Cidade') );
		$form->fieldset( 'wp09' );
		$form->add( new InputText('state','<b>* </b>Estado') );
		$form->fieldset( 'wp10' );
		$form->label('title', 'Tipo de entrega');
		$form->add( new Select('shippingType','<b>* </b>Frete',$this->typeShipping(), 0) );
		$form->fieldset('buttons');
		$form->add( new InputSubmit('btn_save', 'ir para tela de pagamento') );
	
		return $form->get();
	}
}

